package org.lc.stk.web.controller.bank;

import org.lc.stk.model.banks.CourseQuestionBank;
import org.lc.stk.service.bank.CourseQuestionBankService;
import org.lc.stk.web.dto.bank.BankResponse;
import org.lc.stk.web.dto.bank.CourseQuestionBankDTO;
import org.lc.stk.web.response.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/v1/banks/course-question")
@Tag(name = "单课程题库管理", description = "单课程题库的增删改查接口")
@Validated
public class CourseQuestionBankController {

    @Autowired
    private CourseQuestionBankService bankService;

    @PostMapping
    @Operation(summary = "创建单课程题库")
    @PreAuthorize("hasAuthority('BANK_WRITE')")
    public ApiResponse<BankResponse> create(@Valid @RequestBody CourseQuestionBankDTO request) {
        CourseQuestionBank bank = bankService.create(request);
        return ApiResponse.success(BankResponse.fromEntity(bank));
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新单课程题库")
    @PreAuthorize("hasAuthority('BANK_WRITE') and @resourcePermissionEvaluator.hasBankAccess(authentication, #id)")
    public ApiResponse<BankResponse> update(
        @Parameter(description = "题库ID", required = true) @PathVariable Integer id,
        @Valid @RequestBody CourseQuestionBankDTO request) {
        CourseQuestionBank bank = bankService.update(id, request);
        return ApiResponse.success(BankResponse.fromEntity(bank));
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除单课程题库")
    @PreAuthorize("hasAuthority('BANK_WRITE') and @resourcePermissionEvaluator.hasBankAccess(authentication, #id)")
    public ApiResponse<Void> delete(
        @Parameter(description = "题库ID", required = true) @PathVariable Integer id) {
        bankService.delete(id);
        return ApiResponse.success();
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取单课程题库详情")
    @PreAuthorize("hasAuthority('BANK_READ') and @resourcePermissionEvaluator.hasBankAccess(authentication, #id)")
    public ApiResponse<BankResponse> getById(
        @Parameter(description = "题库ID", required = true) @PathVariable Integer id) {
        CourseQuestionBank bank = bankService.getById(id);
        return ApiResponse.success(BankResponse.fromEntity(bank));
    }

    @GetMapping("/course/{courseId}")
    @Operation(summary = "获取课程下的所有题库")
    @PreAuthorize("hasAuthority('BANK_READ')")
    public ApiResponse<List<BankResponse>> listByCourse(
        @Parameter(description = "课程ID", required = true) @PathVariable Integer courseId) {
        List<CourseQuestionBank> banks = bankService.listByCourse(courseId);
        List<BankResponse> responseList = banks.stream()
            .map(BankResponse::fromEntity)
            .collect(Collectors.toList());
        return ApiResponse.success(responseList);
    }

    @GetMapping
    @Operation(summary = "分页查询单课程题库")
    @PreAuthorize("hasAuthority('BANK_READ')")
    public ApiResponse<List<BankResponse>> query(
        @Parameter(description = "课程ID") @RequestParam(required = false) Integer courseId,
        @Parameter(description = "题库名称") @RequestParam(required = false) String name,
        @Parameter(description = "状态：1-在用，0-停用") @RequestParam(required = false) Integer state,
        @Parameter(description = "页码(从0开始)", example = "0") @RequestParam(defaultValue = "0") int page,
        @Parameter(description = "每页大小", example = "10") @RequestParam(defaultValue = "10") int size,
        @Parameter(description = "排序字段") @RequestParam(defaultValue = "id") String sortBy,
        @Parameter(description = "排序方向") @RequestParam(defaultValue = "asc") String sortDirection) {
        
        Sort sort = Sort.by(
            sortDirection.equalsIgnoreCase("desc") ? 
            Sort.Direction.DESC : Sort.Direction.ASC, 
            sortBy
        );

        Page<CourseQuestionBank> resultPage = bankService.query(
            courseId, name, state, 
            PageRequest.of(page, size, sort)
        );

        List<BankResponse> responseList = resultPage.getContent().stream()
            .map(BankResponse::fromEntity)
            .collect(Collectors.toList());

        return ApiResponse.success(
            responseList,
            new ApiResponse.PageInfo(
                resultPage.getNumber(),
                resultPage.getSize(),
                resultPage.getTotalElements(),
                resultPage.getTotalPages()
            )
        );
    }

    @GetMapping("/exists/name/{name}")
    @Operation(summary = "检查题库名称是否存在")
    @PreAuthorize("hasAuthority('BANK_READ')")
    public ApiResponse<Boolean> checkNameExists(
        @Parameter(description = "题库名称", required = true) @PathVariable String name,
        @Parameter(description = "排除的题库ID") @RequestParam(required = false) Integer excludeId,
        @Parameter(description = "课程ID", required = true) @RequestParam Integer courseId) {
        return ApiResponse.success(bankService.isNameExists(name, excludeId, courseId));
    }
}